package middleware

import (
	"context"
	"fmt"
	"hft/Database/admin"
	"hft/db/mongodb/model"
	"hft/global"
	"hft/tools"
	"time"

	"github.com/gin-gonic/gin"
)

// 判断是否需要验证
func JustNeedApi(path string) bool {
	res, err := global.OC_REDIS.Get(fmt.Sprintf("api__%v", path)).Result()

	var api *admin.Api

	if err != nil {
		global.OC_DB.Where("api_path", path).First(&api)

		global.OC_REDIS.Set(fmt.Sprintf("api__%v", path), fmt.Sprintf("%v", api.IsLogger), -1)

		if api.IsLogger == 1 {
			return true
		} else {
			return false
		}
	} else {
		if res == "1" {
			return true
		} else {
			return false
		}
	}
}

func WriteLoggerInToMongoDB(ctx *gin.Context, start time.Time) {

	claims, _ := tools.GetClaims(ctx)

	cost := time.Since(start)

	var body *interface{}

	ctx.ShouldBindJSON(&body)

	var query interface{}

	ctx.ShouldBindQuery(&query)

	var logger = &model.Logger{
		CreateTime: start.Unix(),
		Cost:       int64(cost.Milliseconds()),
		Path:       ctx.Request.URL.Path,
		Code:       ctx.Writer.Status(),
		IP:         ctx.ClientIP(),
		Method:     ctx.Request.Method,
		User:       claims.Username,
		ReqBody:    tools.JsonParse(body),
		Query:      tools.JsonParse(query),
	}

	var loggerDataBaseName = fmt.Sprintf("log_%v", time.Now().Format("20060102"))

	global.OC_MON.Database(global.OC_CONFIG.MongoDB.Logger).Collection(loggerDataBaseName).InsertOne(context.TODO(), logger)

}

// 日志库zap中间件
func Zap() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		var start = time.Now()

		ctx.Next()

		if JustNeedApi(ctx.Request.URL.Path) {
			WriteLoggerInToMongoDB(ctx, start)
		}

	}
}
